package cn.tedu.csmall.product.ex.handle;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e){
        log.warn("程序运行过程中出现了ServiceException");
        log.warn("异常信息: {}",e.getMessage());
        return JsonResult.fail(ServiceCode.ERR_CONFLICT,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e){
        log.warn("程序运行过程中出现了BindException");
        log.warn("异常信息: {}",e.getMessage());
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        log.warn("程序运行过程中出现了ConstraintViolationException");
        log.warn("异常信息: {}",e.getMessage());
        String message = null;
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            message = constraintViolation.getMessage();
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.warn("程序运行过程中出现了ConstraintViolationException");
        log.warn("异常信息: ",e);
        String message = "服务器忙，请稍后再试!";
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,message);
    }
}
